#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct point{
	int x,y,step;
	/*写法一*/
	/*
	 * point(int xx,int yy){
	 * 	  x=xx;
	 * 	  y=yy;
	 * }
	 */
	/*写法二*/
	point(int x,int y,int step):x(x),y(y),step(step){}
	point(){}
}pp;
int n,m,step=-1;
int xx[4]={0,0,1,-1};
int yy[4]={1,-1,0,0};
char a[101][101];
bool a_[101][101];
void bfs();
int main(){
	int i,j;
	memset(a_,false,sizeof(a_));
	cin>>n>>m;
	for(i=1;i<=n;++i){
		for(j=1;j<=m;++j){
			cin>>a[i][j];
			if(a[i][j]=='S'){
				pp = point(i,j,0);
			}
		}
	}
	bfs();
	cout<<step;
	return 0;
}
void bfs(){
	queue<point>q;
	q.push(pp);
	a_[pp.x][pp.y]=true;
	while(!q.empty()){
		point p = q.front();
		q.pop();
		for(int i=0;i<4;++i){
			int tx = p.x + xx[i],ty = p.y + yy[i];
			if(tx>0&&tx<=n&&ty>0&&ty<=m&&!a_[tx][ty]&&a[tx][ty]!='#'){
				point qq = point(tx,ty,p.step+1);
				a_[tx][ty]=true;
				if(a[tx][ty]=='T') step = qq.step;
				q.push(qq);
			}
		}
	}
}